package io.leo.leoutils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.leo.leoutils.bean.Application;

public class AppUtils {


    public static List<Application> getApps(Context context){return getApps(context,true);}

    public static List<Application> getApps(Context context,boolean needIcon) {
        PackageManager pm = context.getPackageManager();
        // 查询所有已经安装的应用程序
        List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);// GET_UNINSTALLED_PACKAGES代表已删除，但还有安装目录的
        List<Application> applications = new ArrayList<>();

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        // 通过getPackageManager()的queryIntentActivities方法遍历,得到所有能打开的app的packageName
        List<ResolveInfo> resolveinfoList = context.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);
        Set<String> allowPackages = new HashSet();
        for (ResolveInfo resolveInfo : resolveinfoList) {
            allowPackages.add(resolveInfo.activityInfo.packageName);
        }

        for (ApplicationInfo app : appInfos) {
            Application application = new Application();
            application.setAppName(app.loadLabel(context.getPackageManager()).toString());
            application.setPackageName(app.packageName);
            if (needIcon)
                application.setIcon(app.loadIcon(context.getPackageManager()));
            if((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0){
                application.setSystemApp(false);
            }else application.setSystemApp(true);

            if (allowPackages.contains(app.packageName)) {
                applications.add(application);
            }
        }

        Collections.sort(applications,(a,b) -> a.appName.compareTo(b.appName));
        return applications;

    }

}
